package com.smtx.service.impl;

import com.smtx.service.Node;
import com.smtx.service.Repository;
import com.smtx.service.SimpleRepository;

import javax.naming.OperationNotSupportedException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: Cyril
 * Date: 17.04.11
 * Time: 2:48
 * To change this template use File | Settings | File Templates.
 */
public class RepositoryImpl extends NodeImpl implements Repository, SimpleRepository {
    protected Map<String, Node> cache = new HashMap<String, Node>();
    protected String root;
    protected String name;

    public RepositoryImpl(String root, String name) throws IOException {
        super(root);
        this.root = root;
        this.name = name;
        if (!isExists())
            create();
    }

    @Override
    public Node getNode(String path) throws IOException {
        if (!cache.containsKey(path)) {
            NodeImpl n = new NodeImpl(root + PATH_SEP + path);
            n.rep = this;
            cache.put(path, n);
        }
        return cache.get(path);
    }

    public static class ReferenceImpl implements Reference {

        String repositoryName;
        String path;

        public ReferenceImpl(String reference) {
            Matcher m = refTpl.matcher(reference);
            if (m.find()) {
                repositoryName = m.group(1);
                path = m.group(2);
            }
        }

        public String getRepositoryName() {
            return repositoryName;
        }

        public String getPath() {
            return path;
        }
    }
}
